package info.motteke.kurumi.swt;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class LoginShell {

    private static int COMMON_SHELL = SWT.TITLE | SWT.BORDER;

    private Display display;

    private Shell shell;

    private Text userIdForm;

    private Text passwordForm;

    private Button ok;

    private String userId;

    private String password;

    public LoginShell(Shell parent) {
        this(parent.getDisplay(), parent, new Shell(parent, SWT.APPLICATION_MODAL| COMMON_SHELL));
    }

    public LoginShell() {
        this(Display.getDefault(), null, new Shell(Display.getDefault(), COMMON_SHELL));
    }

    private LoginShell(Display display, Shell parent, Shell child) {
        this.display = display;
        this.shell = child;

        shell.setLayout(new GridLayout(2, false));
        shell.setText("ログイン");

        GridData gd;

        Label userIdLabel = new Label(shell, SWT.NONE);

        gd = new GridData(GridData.BEGINNING);
        userIdLabel.setLayoutData(gd);
        userIdLabel.setText("ログインID");

        userIdForm = new Text(shell, SWT.BORDER);

        gd = new GridData(GridData.FILL_BOTH);
        gd.minimumWidth = 120;
        userIdForm.setLayoutData(gd);

        Label passwordLabel = new Label(shell, SWT.NONE);
        gd = new GridData(GridData.BEGINNING);
        passwordLabel.setLayoutData(gd);
        passwordLabel.setText("パスワード");


        passwordForm = new Text(shell, SWT.BORDER);

        passwordForm.setEchoChar('.');
        gd = new GridData(GridData.FILL_BOTH);
        gd.minimumWidth = 120;
        passwordForm.setLayoutData(gd);

        ok = new Button(shell, SWT.PUSH);

        gd = new GridData(GridData.END);
        gd.horizontalSpan = 2;
        gd.minimumWidth = 80;

        ok.setLayoutData(gd);
        ok.setText("OK");

        ok.addSelectionListener(new SelectionAdapter(){
            @Override
            public void widgetSelected(SelectionEvent e) {
                userId = userIdForm.getText();
                password = passwordForm.getText();

                shell.close();
            }
        });
    }

    public void start() {
        shell.open();
        shell.pack();

        while(!shell.isDisposed()){
            if(!display.readAndDispatch()){
                display.sleep();
            }
        }

        display.dispose();
    }

    public String getUserId() {
        return userId;
    }

    public String getPassword() {
        return password;
    }
}
